<?php

namespace addons\facrm\controller;

use addons\facrm\library\BackendApi;
use addons\facrm\model\Admin as AdminModel;
use app\admin\model\AdminLog;
use think\Config;
use think\Hook;
use think\Validate;

/**
 * 登录操作
 * @internal
 */
class Index extends BackendApi
{

    protected $noNeedLogin = ['login', 'wxlogin','bind','mplogin'];
    protected $noNeedRight = ['logout','unbind','thirdlist'];
    protected $platforms =['admin_min','admin_mp'] ;//admin_min微信小程序登录标识

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }
    /**
     * 登录[帐号和密码]
     * @ApiMethod (post)
     * @ApiParams(name="username", type="string", required=true, description="帐号")
     * @ApiParams(name="password", type="string", required=true, description="密码")
     * @ApiParams(name="keeplogin", type="string", required=false, description="保持登录，暂时未做")
     */
    public function login()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $keeplogin = $this->request->post('keeplogin');
        $sid=$this->request->post('sid');
        if ($sid){
            session_id($sid);
            session_start();
        }

        $rule = [
            'username' => 'require|length:3,30',
            'password' => 'require|length:3,30',
        ];
        $data = [
            'username' => $username,
            'password' => $password,

        ];
        if (Config::get('fastadmin.login_captcha')) {
            $rule['captcha'] = 'require|captcha';
            $data['captcha'] = $this->request->post('captcha');
        }
        $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
        AdminLog::setTitle(__('移动端帐号登录'));
        $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
        if ($result === true) {
            $admin = $this->auth->getAdmin();
            if ($admin) {
                Hook::listen("admin_login_after", $this->request);
                return $this->success(__("登录成功！"), [
                    'token' => $admin->token,
                    'id' => $admin->id,
                    'username' => $admin->username,
                    'nickname' => $admin->nickname,
                    'avatar' => cdnurl($admin->avatar, true),
                ]);
            }


        }
        $msg = $this->auth->getError();
        $msg = $msg ? $msg : __('Username or password is incorrect');
        $this->error($msg);


    }

    /**
     * 小程序微信登录
     * @ApiMethod (post)
     * @ApiParams(name="code", type="string", required=true, description="code")
     * @ApiParams(name="encrypted_data", type="string", required=true, description="encrypted_data")
     * @ApiParams(name="iv", type="string", required=true, description="iv")
     */
    public function wxlogin()
    {

        $platform='admin_min';
        $model = new AdminModel();
        $post = $this->request->post();
        $third = get_addon_info('third');
        if (!$third || $third['state']!=1) {
            return $this->error(__("请先安装第三方登录插件"));
        }
        $data = $model->minLogin($post);
        if (!$data) {
            return $this->error($model->getError());
        }

        $data['openid'] = $data['openId'];
        $data['unionId'] =isset($data['unionId'])? $data['unionId']:'';
        $data['access_token'] = $data['refresh_token'] = $post['code'];
        $data['expires_in'] = 0;
        $data['userinfo']['nickname'] = $data['nickName'];
        $data['userinfo']['avatar'] = $data['avatarUrl'];
        $third = $model->connects($platform, $data);

        AdminLog::setTitle(__('小程序登录'));
        if ($third) {
            if (isset($third->user_id)&&$third->user_id) {
                $admin = $this->auth->direct($third->user_id);
                if ($admin) {
                    Hook::listen("admin_login_after", $this->request);
                    return $this->success(__("登录成功！"), [
                        'token' => $admin->token,
                        'id' => $admin->id,
                        'username' => $admin->username,
                        'nickname' => $admin->nickname,
                        'avatar' => cdnurl($admin->avatar, true),
                    ]);
                }
                return $this->error(__($this->auth->getError()));
            } else {
                //绑定帐号
                return $this->error(__("跳转到绑定帐号"), ['refresh_token' => $third->refresh_token]);
            }
        }
        return $this->error(__("登录失败，请重试"));
    }

    /**
     * 微信公众号登录
     * @ApiMethod (get)
     * @ApiParams(name="code", type="string", required=true, description="code")
     */
    public function mplogin(){
        $platform='admin_mp';
        $model = new AdminModel();
        $get = $this->request->get();
        $third = get_addon_info('third');
        if (!$third || $third['state']!=1) {
            return $this->error(__("请先安装第三方登录插件"));
        }
        $data = $model->mpLogin($get);
        if (!$data) {
            return $this->error($model->getError());
        }
        if (!isset($data['original']['openid'])){
            return $this->error(__("获取微信登录信息失败"));
        }

        $data_param['openid'] = $data['original']['openid'];
        $data_param['unionId'] =isset($data['original']['unionId'])? $data['original']['unionId']:'';
        $data_param['expires_in'] =3600;
        $data_param['userinfo']['nickname'] = $data['nickname'];
        $data_param['userinfo']['avatar'] = $data['avatar'];
        $data_param['access_token'] = $data['access_token'];
        $data_param['refresh_token'] = $data['refresh_token'];

        $third = $model->connects($platform, $data_param);

        AdminLog::setTitle(__('公众号登录'));
        if ($third) {
            if (isset($third->user_id)&&$third->user_id) {
                $admin = $this->auth->direct($third->user_id);
                if ($admin) {
                    Hook::listen("admin_login_after", $this->request);
                    return $this->success(__("登录成功！"), [
                        'token' => $admin->token,
                        'id' => $admin->id,
                        'username' => $admin->username,
                        'nickname' => $admin->nickname,
                        'avatar' => cdnurl($admin->avatar, true),
                    ]);
                }
                return $this->error(__($this->auth->getError()));
            } else {
                //绑定帐号
                return $this->error(__("跳转到绑定帐号"), ['refresh_token' => $third->refresh_token]);
            }
        }
        return $this->error(__("登录失败，请重试"));
    }


    /**
     * 绑定原有帐号
     * @ApiMethod (POST)
     * @ApiParams(name="username", type="string", required=true, description="帐号")
     * @ApiParams(name="password", type="string", required=true, description="密码")
     * @ApiParams(name="keeplogin", type="string", required=false, description="保持登录，暂时未做")
     * @ApiParams(name="platform", type="string", required=false, description="绑定平台admin_min：小程序 admin_mp：公众号")
     * @ApiParams (name="refresh_token", type="string", required=true, sample="",description="绑定凭证")
     * @ApiReturnParams    (name="token", type="string", required=false, sample="0",description="登录凭证")
     * admin_mp
     * @return array
     */
    public function bind()
    {
        $platform = $this->request->post('platform','admin_min');
        $refresh_token = $this->request->post('refresh_token');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $keeplogin = $this->request->post('keeplogin');
        $sid=$this->request->post('sid');
        if ($sid){
            session_id($sid);
            session_start();
        }
        if (!$refresh_token) {
            $this->error("获取登录信息错误");
        }
        $rule = [
            'username' => 'require|length:3,30',
            'password' => 'require|length:3,30',
        ];
        $data = [
            'username' => $username,
            'password' => $password,

        ];
        if (Config::get('fastadmin.login_captcha')) {
            $rule['captcha'] = 'require|captcha';
            $data['captcha'] = $this->request->post('captcha');
        }
        $validate = new Validate($rule, [], ['username' => __('用户名'), 'password' => __('密码'), 'captcha' => __('验证码')]);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }

        $third = \addons\third\model\Third::where('refresh_token', $refresh_token)->where('platform', $platform)->find();
        if (!$third) {
            $this->error(__('绑定的数据不存在'));
        }
        if ($third->user_id > 0) {
            $this->error(__('已绑定过'));
        }
        if ($third['updatetime'] < (time() - 1800)) {
            $third->delete();
            $this->error(__('请求已经过期，请重试!'));
        }

        AdminLog::setTitle(__('小程序绑定登录'));
        $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
        if ($result === true) {
            $admin = $this->auth->getAdmin();
            if ($admin) {
                Hook::listen("admin_login_after", $this->request);

                $third['user_id'] = $admin->id;
                $third->save();
                return $this->success(__("登录成功！"), [
                    'token' => $admin->token,
                    'id' => $admin->id,
                    'username' => $admin->username,
                    'nickname' => $admin->nickname,
                    'avatar' => cdnurl($admin->avatar, true),
                ]);
            }
        }
        $msg = $this->auth->getError();
        $msg = $msg ? $msg : __('Username or password is incorrect');
        $this->error($msg);

    }

    /**
     * 解绑
     *@ApiParams(name="platform", type="string", required=true, description="平台：admin_min：小程序 admin_mp：公众号")
     */
    public function unbind(){
        $platform = $this->request->post('platform','admin_min');
        if (!in_array($platform,$this->platforms)){
            $this->error(__('平台不存在'));
        }
        $third = \addons\third\model\Third::where('user_id', $this->auth->id)->where('platform', $platform)->find();
        if (!$third) {
            $this->error(__('绑定的数据不存在'));
        }
        $third->delete();
        return $this->success(__("解绑成功！"));
    }

    /**
     * 获取第三方登录绑定列表
     */
    public function thirdlist(){
        $third = get_addon_info('third');
        if (!$third || $third['state']!=1) {
            return $this->error(__("请先安装第三方登录插件"));
        }
        $thirdlist = \addons\third\model\Third::where('user_id', $this->auth->id)
            ->field('id,platform,openname,logintime')
            ->where('platform', 'in',$this->platforms)->select();
        return $this->success('',$thirdlist);

    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        return $this->success(__("退出成功"));
    }

}
